<?php

class XHandler extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

    function clear()
    {
        if (Auth::check()) {
            Auth::logout();
        }    
    }
        
    private function setRegisterFields()
    {
        return array('namefirst'   => Input::get('namefirst'),
                     'namelast'    => Input::get('namelast'),
                     'phonehome'   => Input::get('phonehome'),
                     'phonework'   => Input::get('phonework'),
                     'phonemobile' => Input::get('phonemobile'),
                     'permission'  => 0);        
    }
    
    public function update() 
    {
        $found = User::firstByAttributes(array('username' => Input::get('username')));
        if ($found == null) {
            return Redirect::to('error')->with('err', 'You must be logged in to update your info');
        }
        $attrs = $this->setRegisterFields();
        DB::table('users')->where('id', $found->id)->update($attrs);
        return Redirect::to('start');
    }        
    
    public function register() 
    {
        $this->clear();
        $found = User::firstByAttributes(array('username' => Input::get('username')));
        if ($found != null) {
            return Redirect::to('error')->with('err', 'Username '.$found->username.' already registered');
        }
        $attrs = $this->setRegisterFields();   
        $attrs['username'] = Input::get('username');
        $attrs['password'] = Hash::make(Input::get('password'));
                     
        $id = DB::table('users')->insertGetId($attrs);
        return Redirect::to('login')->with('username', Input::get('username'));
    }
    
    public function logout() 
    {
        $this->clear();
        return Redirect::to('start');
    }
    
	public function login()
	{
        $this->clear();
        $up = array('username' => Input::get('username'),
                    'password' => Input::get('password'));
        if (Auth::attempt($up)) {
            return Redirect::to('start');
        }
        return Redirect::to('error')->with('err', 'username/password combination not recognized');
	}

}
